import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import threading
import joblib
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt


# 创建模型函数 (精简版，带进度更新)
def createModel(progress_bar, plot_frame):
    # 初始化进度条（总进度100%，中文提示）
    def update_progress(desc, step):
        progress_bar["value"] += step
        progress_bar.update_idletasks()
        print(desc)

    update_progress("正在读取数据...", 10)
    names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape',
             'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin',
             'Normal Nucleoli', 'Mitoses', 'Class']
    data = pd.read_csv(
        'https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data',
        names=names)
    data = data.replace(to_replace='?', value=np.nan).dropna()
    x = data.iloc[:, 1:10]
    y = data['Class']
    update_progress("划分训练测试集...", 10)

    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=22)
    update_progress("标准化数据...", 20)

    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    update_progress("模型训练中...", 30)

    estimator = LogisticRegression()
    estimator.fit(x_train, y_train)
    update_progress("评估模型效果...", 10)

    y_scores = estimator.predict_proba(x_test)[:, 1]
    fpr, tpr, thresholds = roc_curve(y_test, y_scores, pos_label=4)
    roc_auc = auc(fpr, tpr)

    # 绘制 ROC 曲线
    fig, ax = plt.subplots(figsize=(6, 5))
    ax.plot(fpr, tpr, color='blue', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')
    ax.plot([0, 1], [0, 1], color='gray', linestyle='--', lw=2)
    ax.set_xlim([0.0, 1.0])
    ax.set_ylim([0.0, 1.05])
    ax.set_xlabel('False Positive Rate')
    ax.set_ylabel('True Positive Rate')
    ax.set_title('Receiver Operating Characteristic (ROC) Curve')
    ax.legend(loc="lower right")

    # 将图像嵌入 Tkinter 界面
    canvas = FigureCanvasTkAgg(fig, master=plot_frame)
    canvas.draw()
    canvas.get_tk_widget().pack()

    update_progress("保存模型文件...", 10)
    joblib.dump(estimator, 'logistic_regression_model.pkl')
    joblib.dump(transfer, 'scaler.pkl')


# 启动模型训练的线程
def start_training(progress_bar, plot_frame):
    thread = threading.Thread(target=createModel, args=(progress_bar, plot_frame))
    thread.start()


# 创建 GUI
def create_gui():
    root = tk.Tk()
    root.title("乳腺癌分类模型系统")
    root.geometry("800x600")

    # 标题标签
    title_label = tk.Label(root, text="乳腺癌分类模型训练", font=("Arial", 16))
    title_label.pack(pady=20)

    # 进度条
    progress_bar = ttk.Progressbar(root, orient="horizontal", length=600, mode="determinate")
    progress_bar.pack(pady=20)

    # 开始训练按钮
    start_button = ttk.Button(root, text="开始训练", command=lambda: start_training(progress_bar, plot_frame))
    start_button.pack(pady=10)

    # ROC 图显示区域
    plot_frame = tk.Frame(root)
    plot_frame.pack(pady=20)

    root.mainloop()


if __name__ == "__main__":
    create_gui()
